import './LoginStyle.sass'
import { loginApi } from '../../api'
import type { FormProps } from 'antd';
import { Button, Checkbox, Form, Input, message } from 'antd';
import type { FieldType } from '../../type/LoginViewType';
import type { LoginApiParams } from '../../type/ApiType';
import { useDispatch, useSelector } from 'react-redux';
import type { UserStore } from '../../type/StoreType';
import { setLoginRemember, setUser } from '../../stores/UserSlice';
import { useNavigate } from 'react-router-dom';

function LoginView () {

  // #region 变量声明
  const { loginRemember } = useSelector((state: { user: UserStore }) => state.user) // 仓库数据
  const dispatch = useDispatch() // 修改仓库数据
  const navigate = useNavigate() // 路由
  // #endregion

  // #region 函数
  // 登录验证函数
  const loginVerification = async (params: LoginApiParams, remember: boolean) => {
    try {
      const res = await loginApi(params) // 线上验证
      // console.log(res)
      if (res.data.code === 0) {
        // 验证成功
        message.open({
          type: 'success',
          content: res.data.msg,
        });
        // 储存登录返回信息
        dispatch(setUser(res.data.data))
        if (remember) dispatch(setLoginRemember({ ...params, remember }))
        // 登录成功跳到首页去
        navigate('/')
      } else {
        message.error(res.data.msg)
        if (remember) dispatch(setLoginRemember({ remember: true }))
      }
    } catch (error) {
      console.log(error)
      if (remember) dispatch(setLoginRemember({ remember: true }))
    }
  }
  // 点击登录后触发
  const onFinish: FormProps<FieldType>['onFinish'] = (values) => {
    console.log('Success:', values);
    if (!values.username || !values.password) return
    if (values.remember === undefined) return
    // 登录验证
    loginVerification({ username: values.username, password: values.password }, values.remember)
  };
  // 验证失败触发
  const onFinishFailed: FormProps<FieldType>['onFinishFailed'] = (errorInfo) => {
    console.log('Failed:', errorInfo);
  };

  // #endregion

  // #region Hooks

  // #endregion

  return (
    <div className="login">
      <Form
        name="login"
        labelCol={{ span: 4 }}
        wrapperCol={{ span: 12 }}
        initialValues={loginRemember}
        onFinish={onFinish}
        onFinishFailed={onFinishFailed}
        autoComplete="off"
        style={{ maxWidth: 600 }}
      >
        <Form.Item>
          <span className='login_title'>登录</span>
        </Form.Item>
        <Form.Item<FieldType>
          label="用户名:"
          name="username"
          rules={[{ required: true, message: '请输入用户名!' }]}
        >
          <Input />
        </Form.Item>

        <Form.Item<FieldType>
          label="密码:"
          name="password"
          rules={[{ required: true, message: '请输入密码!' }]}
        >
          <Input.Password />
        </Form.Item>

        <Form.Item<FieldType> name="remember" valuePropName="checked" label={null}>
          <Checkbox>记住密码?</Checkbox>
        </Form.Item>

        <Form.Item>
          <Button type="primary" htmlType="submit">
            登录
          </Button>
        </Form.Item>
      </Form>
    </div>
  )
}

export default LoginView
